<?php

if(!defined("INDEX"))
    die;

$start_time = microtime();
$start_array = explode(" ", $start_time);
$start_time = $start_array[1] + $start_array[0];

// ---------------------------------------------------------------------------

try {

    session_name(SESSION_NAME);
    session_start();

    $user = User::getAnonymous();

    if(isset($_SESSION['cookie'])) {

        $user_id = User::getIdByCookie($_SESSION['cookie']);

        if($user_id)
            $user = User::getById($user_id);

    } elseif(isset($_COOKIE['auth_hash'])) {

        $user_id = User::getIdByCookie($_COOKIE['auth_hash']);

        if($user_id)
            $user = User::getById($user_id);
    }
    
    if($user->id != 0) {
        // User authorized
        if($user->select_lang) {
            switch($user->lang) {
                default:
                case 'en':
                    set_lang('en_US');
                    break;

                case 'ru':
                    set_lang('ru_RU');
                    break;
            }
        } else {

            set_lang_auto();
        }
    } else {

        set_lang_auto();
    }
 
    $smarty->assign_by_ref('user', $user);

    $cat = $DEFAULT_CAT;

    if(isset($_GET['cat']))
        $cat = $_GET['cat'];

    if(!valid_cat($cat))
        throw new HackException();

    $stats = new Stats;
    $stats->addVisit(
        $_SERVER['REMOTE_ADDR'],
        isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL,
        $_SERVER['REQUEST_URI'],
        $user->id
        );

    include_once("$cat.inc.php");

    $smarty->assign('page_title', _(get_cat_title($cat)));
    $smarty->assign('body', "$cat.tmpl.html");



} catch(HackException $e) {

    $smarty->assign('error', true);
    $smarty->assign('error_img', '/secret/haruhi.jpg');
    $smarty->assign('error_alt', _('Nice try!'));
    $smarty->assign('error_msg', $e->getMessage());

} catch (CoreException $e) {

    $smarty->assign('error', true);
    $smarty->assign('error_img', '/secret/neko.jpg');
    $smarty->assign('error_alt', _('Fatal error!'));
    $smarty->assign('error_msg', _('Core exception occured. Sorry!'));

} catch(Exception $e) {

    $smarty->assign('error', true);
    $smarty->assign('error_img', '/secret/nya.jpg');
    $smarty->assign('error_alt', _('Neko is very sorry!'));
    $smarty->assign('error_msg', $e->getMessage());

}

// ---------------------------------------------------------------------------

$dbo = DBO::getInstance();

$end_time = microtime();
$end_array = explode(" ", $end_time);
$end_time = $end_array[1] + $end_array[0];
$time = round($end_time - $start_time, 2);
$queries = $dbo->queries_count;

$smarty->assign('time', $time);
$smarty->assign('queries', $queries);

$smarty->display('main.tmpl.html');